const express = require('express');
const router = express.Router();
const { body, validationResult } = require('express-validator');
const QA = require('../models/QA');
const auth = require('../middleware/auth');

// 获取问答列表
router.get('/', async (req, res) => {
    try {
        const { page = 1, limit = 10, tag, search } = req.query;
        const query = {};

        if (tag) {
            query['question.tags'] = tag;
        }

        if (search) {
            query.$or = [
                { 'question.title': { $regex: search, $options: 'i' } },
                { 'question.content': { $regex: search, $options: 'i' } }
            ];
        }

        const qaList = await QA.find(query)
            .populate('question.author', 'username avatar')
            .populate('answers.author', 'username avatar')
            .sort({ 'question.createdAt': -1 })
            .limit(limit * 1)
            .skip((page - 1) * limit);

        const count = await QA.countDocuments(query);

        res.json({
            qaList,
            totalPages: Math.ceil(count / limit),
            currentPage: page
        });
    } catch (error) {
        res.status(500).json({ message: '服务器错误' });
    }
});

// 发布问题
router.post('/questions', auth, [
    body('title').trim().notEmpty().withMessage('标题不能为空'),
    body('content').trim().notEmpty().withMessage('内容不能为空')
], async (req, res) => {
    try {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }

        const { title, content, tags } = req.body;
        const qa = new QA({
            question: {
                title,
                content,
                tags: tags || [],
                author: req.user._id
            }
        });

        await qa.save();
        res.status(201).json(qa);
    } catch (error) {
        res.status(500).json({ message: '服务器错误' });
    }
});

// 回答问题
router.post('/:qaId/answers', auth, [
    body('content').trim().notEmpty().withMessage('回答内容不能为空')
], async (req, res) => {
    try {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }

        const qa = await QA.findById(req.params.qaId);
        if (!qa) {
            return res.status(404).json({ message: '问题不存在' });
        }

        qa.answers.push({
            content: req.body.content,
            author: req.user._id
        });

        await qa.save();
        res.status(201).json(qa);
    } catch (error) {
        res.status(500).json({ message: '服务器错误' });
    }
});

// 采纳答案
router.put('/:qaId/answers/:answerId/accept', auth, async (req, res) => {
    try {
        const qa = await QA.findById(req.params.qaId);
        if (!qa) {
            return res.status(404).json({ message: '问题不存在' });
        }

        if (qa.question.author.toString() !== req.user._id.toString()) {
            return res.status(403).json({ message: '只有提问者可以采纳答案' });
        }

        const answer = qa.answers.id(req.params.answerId);
        if (!answer) {
            return res.status(404).json({ message: '答案不存在' });
        }

        // 重置所有答案的采纳状态
        qa.answers.forEach(a => a.isAccepted = false);
        answer.isAccepted = true;

        await qa.save();
        res.json(qa);
    } catch (error) {
        res.status(500).json({ message: '服务器错误' });
    }
});

// 创建问题
router.post('/', auth, async (req, res) => {
    try {
        const { question, content } = req.body;

        const qa = new QA({
            question,
            content,
            author: req.user._id
        });

        await qa.save();

        res.status(201).json({
            message: '问题创建成功',
            qa
        });
    } catch (error) {
        res.status(500).json({ message: '服务器内部错误' });
    }
});

// 获取问题列表
router.get('/', async (req, res) => {
    try {
        const qas = await QA.find()
            .populate('author', 'username')
            .populate('answers.author', 'username')
            .sort({ createdAt: -1 });

        res.json({ qas });
    } catch (error) {
        res.status(500).json({ message: '服务器内部错误' });
    }
});

// 获取单个问题
router.get('/:id', async (req, res) => {
    try {
        const qa = await QA.findById(req.params.id)
            .populate('author', 'username')
            .populate('answers.author', 'username');

        if (!qa) {
            return res.status(404).json({ message: '问题不存在' });
        }

        res.json({ qa });
    } catch (error) {
        res.status(500).json({ message: '服务器内部错误' });
    }
});

// 更新问题状态
router.put('/:id/status', auth, async (req, res) => {
    try {
        const { status } = req.body;
        const qa = await QA.findById(req.params.id);

        if (!qa) {
            return res.status(404).json({ message: '问题不存在' });
        }

        // 检查是否是问题作者
        if (qa.author.toString() !== req.user._id.toString()) {
            return res.status(403).json({ message: '没有权限修改此问题' });
        }

        qa.status = status;
        await qa.save();

        res.json({
            message: '问题状态更新成功',
            qa
        });
    } catch (error) {
        res.status(500).json({ message: '服务器内部错误' });
    }
});

module.exports = router; 